package mysql.controller;

import mysql.entity.User;
import mysql.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Instant;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserRepository userRepository;

    @PostMapping
    @Transactional
    public User addUser() {
        User user = new User();
        user.setUsername("zhp" + Math.random());
        user.setPassword("654321");
        // todo: 这里无效，如何有效？
        user.setCreateBy("zhp");
        user.setCreateTime(Instant.now().minusSeconds(600L));
        User saveUser = userRepository.save(user);
        return saveUser;
    }

    @GetMapping
    public List<User> findAll() {
        return userRepository.findAll();
    }

    @GetMapping("/page")
    public Page<User> pageAll(Pageable pageable) {
        return userRepository.findAll(pageable);
    }
}
